package com.tduck.cloud.report.data.db;


import com.tduck.cloud.common.exception.BusinessException;
import com.tduck.cloud.report.data.entity.DataSourceConfig;
import com.zaxxer.hikari.pool.HikariPool;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 报表数据连接工厂
 */
@Slf4j
@UtilityClass
public class ReportDataConnectionFactory {


    /**
     * 所有数据源的连接池存在map里
     */
    private Map<String, HikariPool> poolMap = new ConcurrentHashMap<>();

    private Object lock = new Object();

    /**
     * 获取连接池
     *
     * @param dataSourceConfig
     * @return
     */
    public HikariPool getJdbcConnectionPool(DataSourceConfig dataSourceConfig) {
        String url = dataSourceConfig.getUrl();
        if (!poolMap.containsKey(url)) {
            synchronized (lock) {
                if (!poolMap.containsKey(url)) {
                    HikariPool pool = HikariPoolBuilder.builder().build().dataSource(url,
                            dataSourceConfig.getUsername(), dataSourceConfig.getPassword());
                    poolMap.put(url, pool);
                    log.info("创建连接池成功：{}", dataSourceConfig.getUrl());
                }
            }
        }
        return poolMap.get(url);
    }


    /**
     * 测试连接是否正常
     *
     * @param dataSourceConfig
     */
    public static void testJdbcConnectionPool(DataSourceConfig dataSourceConfig) {
        HikariPool hikariPool = HikariPoolBuilder.builder().build().dataSource(dataSourceConfig.getUrl(),
                dataSourceConfig.getUsername(), dataSourceConfig.getPassword());
        try {
            Connection unPooledConnection = hikariPool.getConnection();
            String catalog = unPooledConnection.getCatalog();
            log.info("数据库测试连接成功：{}", catalog);
            unPooledConnection.close();
        } catch (SQLException e) {
            log.error("error", e);
            if (e.getCause() instanceof ClassNotFoundException) {
                throw new BusinessException("数据库驱动不存在" + e.getMessage());
            } else {
                throw new BusinessException("数据库连接失败" + e.getMessage());
            }
        }
    }


}
